package com.charging.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.charging.common.WePublicUtils;
import com.charging.common.constant.Constants;
import com.charging.common.core.controller.BaseController;
import com.charging.common.core.domain.AjaxResult;
import com.charging.common.core.domain.entity.SysUser;
import com.charging.common.core.domain.model.LoginUser;
import com.charging.common.utils.DateUtils;
import com.charging.common.utils.http.HttpUtils;
import com.charging.system.domain.*;
import com.charging.system.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//@RequestMapping("/auth")
@RestController
public class AuthController extends BaseController {

    @Resource
    private IKxUserInfoService kxUserInfoService;
    @Resource
    private IKxChargingRecordService kxChargingRecordService;
    @Resource
    private IKxEquipService kxEquipService;
    @Resource
    private IKxChargingSchemeService kxChargingSchemeService;
    @Resource
    private IKxEquipSchemeService kxEquipSchemeService;
    @Resource
    private WePublicUtils wePublicUtils;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private IKxRechargeSchemeService kxRechargeSchemeService;

    /**
     * 登录成功后获取用户信息
     * @return
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public AjaxResult getUserInfo(){
        logger.info("=================");
        LoginUser loginUser = getLoginUser();
        KxUserInfo kxUserInfo = kxUserInfoService.selectKxUserInfoByUserId(loginUser.getUserId());
        JSONObject info = new JSONObject();
// 用户基本信息 账户、昵称、头像、余额、优惠余额
        info.put("id",loginUser.getUserId());
        info.put("username",loginUser.getUser().getUserName());
        info.put("name",loginUser.getUser().getNickName());
        info.put("avatar",loginUser.getUser().getAvatar()==null?"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif":loginUser.getUser().getAvatar());
        info.put("balance",kxUserInfo.getBalance());
        info.put("give",kxUserInfo.getGive());
        info.put("subscribe","-1");
        info.put("commonUsed",kxUserInfo.getCommonUsed());
        info.put("subscribe",1);
        // 获取当前用户的充电状况

        KxChargingRecord kxChargingRecord = new KxChargingRecord();
        kxChargingRecord.setUserId(loginUser.getUserId());
        kxChargingRecord.setChargingStatus(Constants.ChargingStatus.INTCHARGING);
        List<KxChargingRecord> kxChargingRecords = kxChargingRecordService.selectKxChargingRecordList(kxChargingRecord);
        if(kxChargingRecords.size()>0){
            info.put("chargingStatus",Constants.ChargingStatus.INTCHARGING);
        }else {
            info.put("chargingStatus",Constants.ChargingStatus.ENDCHARGING);
        }
        /**
         * 充值方案获取
         */

        //获取当前用户的充值方案
        KxRechargeScheme kxRechargeScheme = kxRechargeSchemeService.selectKxRechargeSchemeByRechargeSchemeId(100L);
        info.put("rechargeScheme",kxRechargeScheme);

        return AjaxResult.success("",info);
    }

    /**
     *用户进入开始充电页面获取设备信息
     */
    @RequestMapping(value = "/getStartChargingEquipInfo", method = RequestMethod.GET)
    public AjaxResult getStartChargingEquipInfo(String equipNo , String channelNo){

        JSONObject info = new JSONObject();
        KxEquip kxEquip = kxEquipService.getKxEquipByEquipNo(equipNo);
        info.put("equipId",kxEquip.getEquipId());
        info.put("equipNo",kxEquip.getEquipNo());
        info.put("channelNo",channelNo);
        info.put("equipType",kxEquip.getEquipType());
        info.put("equipName",kxEquip.getEquipName());
        KxChargingScheme kxChargeScheme = kxChargingSchemeService.selectKxChargingSchemeByChargingSchemeId(kxEquip.getChargingSchemeId());
        info.put("kxChargeScheme",kxChargeScheme);
        KxEquipScheme kxEquipScheme = kxEquipSchemeService.selectKxEquipSchemeByEquipSchemeId(kxEquip.getEquipSchemeId());
        info.put("kxEquipScheme",kxEquipScheme);
        LoginUser loginUser = getLoginUser();
        KxUserInfo kxUserInfo = kxUserInfoService.selectKxUserInfoByUserId(loginUser.getUserId());
        info.put("balance",kxUserInfo.getBalance());
        info.put("give",kxUserInfo.getGive());
        return AjaxResult.success("",info);
    }

    /**
     * 获取充电中的插座
     */
    @RequestMapping(value = "/getUsedChannels", method = RequestMethod.GET)
    public AjaxResult getUsedChannels(String equipNo){
        JSONObject info = new JSONObject();
        KxEquip kxEquip = kxEquipService.getKxEquipByEquipNo(equipNo);
        info.put("equipId",kxEquip.getEquipId());
        //
        info.put("equipNo",kxEquip.getEquipNo());
        info.put("equipType",kxEquip.getEquipType());
        info.put("equipName",kxEquip.getEquipName());
        info.put("channelNum",kxEquip.getChannelNum());// 插座总数
        // 获取充电中的插座号
        KxChargingRecord kxChargingRecord = new KxChargingRecord();
        kxChargingRecord.setEquipId(kxEquip.getEquipId());
        kxChargingRecord.setChargingStatus(Constants.ChargingStatus.INTCHARGING);
        List<Integer> kxChargingRecordList = kxChargingRecordService.getChargingChannelNos(kxChargingRecord);
        info.put("chargingChannels",kxChargingRecordList);
        return AjaxResult.success("",info);
    }
    /**
     * 获取用户的常用电站
     * @return
     * code,msg,data:
     *	eq
     */
    @ApiOperation(value = "获取用户的常用电站", notes = "")
    @RequestMapping(value = "/getCommonUsed", method = RequestMethod.GET)
    public AjaxResult getCommonUsed(){
        KxUserInfo kxUserInfo = kxUserInfoService.selectKxUserInfoByUserId(getUserId());
        if(ObjectUtils.isNotEmpty(kxUserInfo.getCommonUsed())){
            JSONObject info = new JSONObject();
            KxEquip kxEquip = kxEquipService.selectKxEquipByEquipId(kxUserInfo.getCommonUsed());
            info.put("equipId",kxEquip.getEquipId());
            info.put("equipNo",kxEquip.getEquipNo());
            info.put("equipType",kxEquip.getEquipType());
            info.put("equipName",kxEquip.getEquipName());
            info.put("channelNum",kxEquip.getChannelNum());// 插座总数
            // 获取充电中的插座号
            KxChargingRecord kxChargingRecord = new KxChargingRecord();
            kxChargingRecord.setEquipId(kxEquip.getEquipId());
            kxChargingRecord.setChargingStatus(Constants.ChargingStatus.INTCHARGING);
            List<Integer> kxChargingRecordList = kxChargingRecordService.getChargingChannelNos(kxChargingRecord);
            info.put("chargingChannels",kxChargingRecordList);
            return AjaxResult.success("",info);
        }else {
            return AjaxResult.error("没有常用电站");
        }
    }

    @ApiOperation(value = "获取用户关注公众号状态和金额状态", notes = "")
    @RequestMapping(value = "/getUserSubAndBalance", method = RequestMethod.GET)
    public AjaxResult getUserSubAndBalance(){
        KxUserInfo kxUserInfo = kxUserInfoService.selectKxUserInfoByUserId(getUserId());
        JSONObject info = new JSONObject();
        if(wePublicUtils.checkRequestClient() == Constants.TranType.WEIXIN){
            String reUserInfo = wePublicUtils.getWePublicUserInfo(kxUserInfo.getOpenId(),Constants.kxSystemInfo.getWxAppId(),Constants.kxSystemInfo.getWxAppSecret());
            JSONObject reUser = JSON.parseObject(reUserInfo);

            info.put("subscribe",reUser.getString("subscribe"));// subscribe = 1 表示关注公众号能获取信息， =0 表示没有关注公众号 让用户识别二维码关注
            info.put("publicInfo",Constants.kxSystemInfo.getPublicQr());
            info.put("publicName",Constants.kxSystemInfo.getPublicName());
        }else{
//            info.put("subscribe",wePublicUtils.aliUserIsFollow(account.getThirdIdTow()));
        }
        info.put("balance",kxUserInfo.getBalance());
        return AjaxResult.success("",info);
    }

    /**
     * 微信公众号获取用户详细信息，用户需要同意获取
     * @param code
     * @return
     */
    @RequestMapping(value = "/getWeUserSubInfo", method = RequestMethod.GET)
    public AjaxResult getWeUserSubInfo(String code ){
        String res = wePublicUtils.getWeUserSubInfo(code,Constants.kxSystemInfo.getWxAppId(),Constants.kxSystemInfo.getWxAppSecret());
        JSONObject resJson = JSONObject.parseObject(res);
        if (!resJson.containsKey("errcode")) {
            String access_token = resJson.getString("access_token");
            String openId = resJson.getString("openid");
            logger.info("获取微信公众号客户端 accessToken : {},openid:{}",access_token,openId);
            String param = "access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
            res = HttpUtils.sendGet("https://api.weixin.qq.com/sns/userinfo",param);
            resJson = JSONObject.parseObject(res);
            if (!resJson.containsKey("errcode")) {
                String nickname = resJson.getString("nickname");
                String headimgurl = resJson.getString("headimgurl");
                SysUser newAccount = new SysUser();
                newAccount.setAvatar(headimgurl);
                newAccount.setNickName(filterEmoji(nickname));
                newAccount.setUserId(getUserId());
                sysUserService.updateUser(newAccount);
                return AjaxResult.success("获取微信用户信息成功");
            }else {
                return AjaxResult.error("获取微信用户信息失败");
            }
        }else {
            return AjaxResult.error("拉取微信用户信息失败");
        }
    }
    public static String filterEmoji(String source) {
        if (source != null) {
            Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                    Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                source = emojiMatcher.replaceAll("");
                return source;
            }
            return source;
        }
        return source;
    }


    /**
     * 用户获取服务电话
     * @return
     */
    @RequestMapping(value = "/getCallNo", method = RequestMethod.GET)
    public AjaxResult getCallNo(){

        return AjaxResult.success("1111111");
    }

    /**
     * 用户获取帮助文档
     * @return
     */
    @RequestMapping(value = "/getHelpImage", method = RequestMethod.GET)
    public AjaxResult getHelpImage(){
        return AjaxResult.success();
    }

    /**
     * 获取当前用户的充电记录
     * @return
     */
    @RequestMapping(value = "/getUserChargingList", method = RequestMethod.GET)
    public AjaxResult getUserChargingList(){
        KxChargingRecord kxChargingRecord = new KxChargingRecord();
        kxChargingRecord.setUserId(getUserId());
        kxChargingRecord.setChargingStatus(Constants.ChargingStatus.INTCHARGING);
        List<KxChargingRecord> kxChargingRecords = kxChargingRecordService.selectKxChargingRecordList(kxChargingRecord);
        return AjaxResult.success("",kxChargingRecords);
    }


    /**
     * 获取充电信息
     * @return
     */
    @RequestMapping(value = "/getChargingInfo", method = RequestMethod.GET)
    public AjaxResult getChargingInfo(Long equipId, Integer channelNo){
        // 查询出充电桩和插座的充电状态
        KxChargingRecord kxChargingRecord = new KxChargingRecord();
        kxChargingRecord.setChargingStatus(Constants.ChargingStatus.INTCHARGING);
        kxChargingRecord.setEquipId(equipId);
        kxChargingRecord.setChannelNo(channelNo);
        List<KxChargingRecord> kxChargingRecords = kxChargingRecordService.selectKxChargingRecordList(kxChargingRecord);
        if(kxChargingRecords.size()==0){
            return AjaxResult.error("充电已经结束");
        }else {
            JSONObject info = new JSONObject();
            kxChargingRecord =  kxChargingRecords.get(0);
            info.put("amount",kxChargingRecord.getAmount().setScale(2, RoundingMode.DOWN)); // 消费金额
            Long charge_minutes = ChronoUnit.MINUTES.between(
                    Instant.ofEpochMilli(kxChargingRecord.getCreateTime().getTime()),
                    Instant.ofEpochMilli(kxChargingRecord.getUpdateTime().getTime()));

            info.put("charge_minutes",charge_minutes);// 充电时长
            KxEquip kxEquip = kxEquipService.selectKxEquipByEquipId(equipId);
            info.put("equipName",kxEquip.getEquipName());
            info.put("equipNo",kxEquip.getEquipNo());
            info.put("equipType",kxEquip.getEquipType());
            // 当前消费度数
            info.put("degree",kxChargingRecord.getDegree());
            // 充电模式
            if (kxChargingRecord.getPlanChargingTime() ==0){
                info.put("chargingModel","充满自停");
            }else {
                info.put("chargingModel","计划充电"+kxChargingRecord.getPlanChargingTime()+"小时");
            }
            // 开始充电时间
            info.put("startTime", DateUtils.parseDateToStr("MM-dd HH:mm:ss",kxChargingRecord.getCreateTime()));
            // 当前功率
            info.put("chargingPower",kxChargingRecord.getChargingPower());
            // 最大功率
            info.put("maxChargingPower",kxChargingRecord.getMaxChargingPower());
            // 获取充电记录编号
            info.put("chargingRecordId",kxChargingRecord.getChargingRecordId());
            return AjaxResult.success(info);
        }
    }



}
